package com.yunxin.facerecognition.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.common.activity.BaseActivity;
import com.common.network.help.Error;
import com.common.widget.NetworkToast;
import com.yunxin.facerecognition.R;
import com.yunxin.facerecognition.app.MyApp;
import com.yunxin.facerecognition.databinding.FaceRecognitionActivityRegistrationBinding;
import com.yunxin.facerecognition.network.operate.FaceRecognitionFileUploadOperateRequest;
import com.yunxin.facerecognition.network.original.faceRecognition.RegistrationOriginal;
import com.yunxin.facerecognition.network.request.faceRecognition.UploadFileRequest;
import com.yunxin.facerecognition.network.response.freceRecognition.RegistrationResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;

import id.zelory.compressor.Compressor;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;


/**
 * Created by cms466 on 2017/3/19.
 */

public class RegistrationActivity extends BaseActivity {

    private static final String TAG = "RegistrationActivity";
    FaceRecognitionActivityRegistrationBinding binding;

    private String photoPath = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                for (String photo : photos) {
                    Glide.with(RegistrationActivity.this).load(photo).into(binding.faceRecognitionActivityRegistrationIvPhotoChoose);
                    new Compressor(this)
                            .compressToFileAsFlowable(new File(photo))
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<File>() {
                                @Override
                                public void accept(File file) {
                                    Log.d("MyCameraPictureCallback", file.getAbsolutePath());
                                    photoPath = file.getAbsolutePath();
                                }
                            }, new Consumer<Throwable>() {
                                @Override
                                public void accept(Throwable throwable) {
                                    throwable.printStackTrace();
                                }
                            });

                }
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        binding = DataBindingUtil.setContentView(this, R.layout.face_recognition_activity_registration);

        initData();
        initView();
        initListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initData() {

    }

    private void initListener() {
        binding.faceRecognitionActivityRegistrationBtnRegistration.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toRegistration();
            }
        });

        binding.faceRecognitionActivityRegistrationBtnPhotoChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toChoosePhoto();
            }
        });
    }

    private void initView() {
        binding.faceRecognitionActivityRegistrationUsernameWrapper.setHint("用户");
        binding.faceRecognitionActivityRegistrationCompanyWrapper.setHint("公司");
        binding.faceRecognitionActivityRegistrationMobileWrapper.setHint("手机");
    }

    private void uploadFileReq(File file, String username, String company, String mobile) {
        UploadFileRequest uploadFileRequest = new UploadFileRequest(new RegistrationResponse(), new RegistrationOriginal());

        uploadFileRequest.setHttpUrl(MyApp.Url+"/api.php/Index/");

        uploadFileRequest.setFileUrl(MyApp.Url+"/api.php/Index/reg");

        //上传的文件
        if (file.exists()) {

            uploadFileRequest.setFileUpload(file);

            FaceRecognitionFileUploadOperateRequest.instance().faceRecognitionFileUpload(uploadFileRequest, username, company, mobile, file.getName());
        } else {
            Toast.makeText(this, "该文件不存在", Toast.LENGTH_SHORT).show();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void uploadFileResp(RegistrationResponse registrationResponse) {
        if (!TextUtils.isEmpty(registrationResponse.getError())) {
            Log.e(TAG, "1------------ =" + registrationResponse.getError());
            if (registrationResponse.getError().equals(Error.ERROR_NETWORK_IS_NOT_AVAILABLE)
                    || registrationResponse.getError().equals(Error.ERROR_NET_TIMEOUT)) {
                NetworkToast.makeText(getApplicationContext()).show();
            }else {
                Toast.makeText(this, registrationResponse.getError(), Toast.LENGTH_SHORT).show();
            }
        } else {
            RegistrationOriginal registrationOriginal = registrationResponse.getData();
            if (registrationOriginal != null) {
                Toast.makeText(this, registrationOriginal.getMsg(), Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }


    private void toRegistration() {
        String username = binding.faceRecognitionActivityRegistrationUsernameWrapper.getEditText().getText().toString();
        String company = binding.faceRecognitionActivityRegistrationCompanyWrapper.getEditText().getText().toString();
        String mobile = binding.faceRecognitionActivityRegistrationMobileWrapper.getEditText().getText().toString();

        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "用户不能为空", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(company)) {
            Toast.makeText(this, "公司不能为空", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(mobile)) {
            Toast.makeText(this, "手机不能为空", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(photoPath)) {
            Toast.makeText(this, "图片不能为空", Toast.LENGTH_SHORT).show();
        } else {
            uploadFileReq(new File(photoPath), username, company, mobile);
        }
    }

    private void toChoosePhoto() {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(true)
                .setShowGif(false)
                .setPreviewEnabled(false)
                .start(RegistrationActivity.this, PhotoPicker.REQUEST_CODE);
    }
}
